package com.briup.web.servlet;

import com.briup.bean.Customer;
import com.briup.service.ICustomerService;
import com.briup.service.impl.ICustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/checkUsername")
public class CheckUsername4AjaxServlet extends HttpServlet {
    private ICustomerService customerService = new ICustomerServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 0.设置编码

        // 1.接收用户名
        String username = request.getParameter("username");
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        System.out.println(username);
        // 2.调用 service层 完成查询 返回值 customer
        Customer customerDB = null;
        customerDB = customerService.findCustomerByName(username);

        // 3.写回信息
        if (customerDB != null) {
            response.getWriter().println("0");
        } else if (username.trim().equals("")) {
            response.getWriter().println("1");
        } else {
            response.getWriter().println("2");
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}